package com.example.permission.controller;

import com.example.permission.entity.User;
import com.example.permission.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/users")
public class UserController extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = (UserService) getServletContext().getAttribute("userService");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        if ("detail".equals(action)) {
            // 任务一：查询特定用户及其角色
            String username = request.getParameter("username");
            if (username != null && !username.trim().isEmpty()) {
                User user = userService.getUserWithRolesByUsername(username);
                request.setAttribute("user", user);
                request.getRequestDispatcher("/views/user-detail.jsp").forward(request, response);
                return;
            }
        } else if ("search".equals(action)) {
            // 任务三：综合查询用户
            String username = request.getParameter("username");
            String email = request.getParameter("email");
            String statusStr = request.getParameter("status");
            Integer status = null;

            if (statusStr != null && !statusStr.trim().isEmpty()) {
                status = Integer.parseInt(statusStr);
            }

            List<User> users = userService.searchUsersWithDetails(username, email, status);
            request.setAttribute("users", users);
            request.getRequestDispatcher("/views/user-list.jsp").forward(request, response);
            return;
        }

        // 默认显示用户列表（分页）
        String pageStr = request.getParameter("page");
        int page = (pageStr != null) ? Integer.parseInt(pageStr) : 1;
        int pageSize = 10;

        List<User> users = userService.getUsersByPage(page, pageSize);
        int totalCount = userService.getUserCount();
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        request.setAttribute("users", users);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.getRequestDispatcher("/views/user-list.jsp").forward(request, response);
    }
}